#!/usr/bin/python
# -*- coding: UTF-8 -*-

import requests
import json
import urllib

root_url = 'http://127.0.0.1:8000'

json_list = ["./data.json"]


def load_data():
    data_list = []
    for json_data in json_list:
        with open(json_data, "r") as data:
            data_list.extend(json.load(data))
    return data_list


def result(session, data_list):
    global response
    print('test session headers: ', session.cookies.get_dict())
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    for data in data_list:
        if data['running'] is True:
            if "get" == data['method']:
                params = ''
                if 'data' in data:
                    params = '?' + urllib.urlencode(data['data'])
                response = session.get(url=root_url + data['url'] + params, headers=headers)
            elif "post" == data['method']:
                params = ''
                if 'data' in data:
                    params = json.dumps(data['data'])
                response = session.post(url=root_url + data['url'], data=params, headers=headers)
            elif "put" == data['method']:
                params = ''
                if 'data' in data:
                    params = json.dumps(data['data'])
                response = session.put(url=root_url + data['url'], data=params, headers=headers)
            elif "delete" == data['method']:
                params = ''
                if 'data' in data:
                    params = json.dumps(data['data'])
                response = session.delete(url=root_url + data['url'], data=params, headers=headers)
            print(data['description'])
            print("-------status: " + str(response.status_code))
            print("-------result: " + response.text)
            print(response.headers)


if __name__ == '__main__':
    session = requests.session()
    result(session=session, data_list=load_data())
